<script setup lang="ts">
import {nextTick, onMounted, reactive, ref} from "vue";
import useRoleStore from "@/store/modules/role.ts";
import {DeleteFilled, DocumentAdd, Edit, FolderAdd, Refresh, Search, User} from "@element-plus/icons-vue";
import {toDate} from "@/utils";
import {ElMessage, type FormInstance} from "element-plus";
import type {TRoleInfo, TRoleParams} from "@/api/role/type.ts";
import useMenuStore from "@/store/modules/menu.ts";
import useAdmin from "@/store/modules/admin.ts";
const dialogVisible = ref<boolean>(false);
const formRef = ref<FormInstance>();
const drawer = ref<boolean>(false);
const roleStore = useRoleStore();
const menuStore = useMenuStore();
const adminStore = useAdmin();
const roleForm = reactive<TRoleParams>({
    "_id":"",
    // 权限名称
    "name":"",
    // 权限说明
    "desc":"",
    // 权限标识
    "sign":"",
    // 排序
    "sort":1
})
const onSearchHandler = async function(){
    if(roleStore.keyword.length===0){
        ElMessage.error("请输入搜索的关键词！");
        return;
    }
    await roleStore.getSysRoleListAsync();
}
// 修改表单
const editForm = function (row:TRoleInfo) {
    const {_id,name,sign,sort,desc} = row;
    Object.assign(roleForm,{
        _id,
        // 权限名称
        name,
        // 权限说明
        desc,
        // 权限标识
        sign,
        // 排序
        sort
    })
    dialogVisible.value = true;
    formRef.value?.resetFields();
}
const drawerRef = ref();
const roleId = ref();
// 打开抽屉
const onDrawerHandlere = function (permissionIds:string[],id:string){
    drawer.value = true;
    roleId.value = id;
    console.log("permissionIds",permissionIds)
    nextTick(()=>{
        drawerRef.value.setCheckedKeys(permissionIds);
    })
    // drawerRef.value.setCheckedKeys(permissionIds);

}
// 重置
const onResetHandler = async function(){
    roleStore.keyword = "";
    await roleStore.getSysRoleListAsync();
}
// 提交表单
const submitForm = function () {
    formRef.value?.validate(async (valid) => {
        if (valid) {
            if(roleForm._id && roleForm._id.length>0)
                await roleStore.putSysRoleAsync(roleForm);
            else await roleStore.postSysRoleAsync(roleForm);
            cancelForm();
        }
    })
}
// 取消表单
const cancelForm = function () {
    Object.assign(roleForm, {
        "_id":"",
        // 权限名称
        "name":"",
        // 权限说明
        "desc":"",
        // 权限标识
        "sign":"",
        // 排序
        "sort":1
    });
    dialogVisible.value = false;


}
const btnHandler = async function(){
    console.log(roleId.value,drawerRef.value.getCheckedKeys())
    await roleStore.putSysRoleDoAssignAsync(roleId.value,drawerRef.value.getCheckedKeys());
    drawer.value = false;
}
onMounted(async ()=>{
    await roleStore.getSysRoleListAsync();
    await menuStore.getSysAllMenuAsync();
})
defineOptions({
    name:"SysRole"
})
</script>

<template>
    <el-card>
        <el-form @submit.native.prevent @keyup.enter="onSearchHandler" :inline="true" class="demo-form-inline">
            <el-form-item>
                <el-input  :style="{width:'180px'}" v-model="roleStore.keyword" placeholder="请输入搜索的关键词" clearable />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :icon="Search" @click="onSearchHandler">搜索</el-button>
                <el-button  :icon="Refresh" @click="onResetHandler">重置</el-button>
                <el-button type="success" :icon="FolderAdd" @click="dialogVisible=true;formRef?.resetFields();">添加权限</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <el-table row-key="_id" border :data="roleStore.roleList"
              style="width: 100%;margin-top:5px;height:calc(100vh - 165px) ">
        <el-table-column prop="name" label="角色名称"  align="center" min-width="150"/>
        <el-table-column prop="sign" label="角色标识"  align="center" min-width="120"/>
        <el-table-column prop="sort" label="排序" align="center" min-width="100"/>
        <el-table-column prop="desc" label="描述" min-width="300"/>
        <el-table-column align="center" label="创建时间" width="180">
            <template #default="scope">
                <el-text>{{ toDate(scope.row.createTime) }}</el-text>
            </template>
        </el-table-column>
        <el-table-column align="center" label="修改时间" width="180">
            <template #default="scope">
                <el-text>{{ toDate(scope.row.updateTime) }}</el-text>
            </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="200">
            <template #default="scope">
                <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="编辑菜单"
                    :enterable="false"
                    placement="top"
                >
                    <el-button @click="editForm(scope.row)" type="success" :icon="Edit" circle/>
                </el-tooltip>
                <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="删除菜单"
                    :enterable="false"
                    placement="top-end"
                >
                    <el-button @click="deleteManuHandler(scope.row._id)" :disabled="scope.row.children && scope.row.children.length>0" type="danger" :icon="DeleteFilled" circle/>
                </el-tooltip>
                <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="分配权限"
                    :enterable="false"
                    placement="top-end"
                >
                    <el-button @click="onDrawerHandlere(scope.row.permissionIds,scope.row._id)" type="warning" :icon="User" circle/>
                </el-tooltip>
            </template>
        </el-table-column>
    </el-table>
    <el-dialog
        v-model="dialogVisible"
        :title="(roleForm._id.length>0?'修改':'添加')+'权限'"
        width="500"
        :close-on-click-modal="false"
        :show-close="false"
    >
        <el-form
            ref="formRef"
            v-if="dialogVisible"
            style="max-width: 600px"
            :model="roleForm"
            label-width="auto"
            class="demo-dynamic"
        >
            <el-form-item prop="name" label="名称：" :rules="[{
                        required: true,
                        message: '请输入权限名称',
                        trigger: 'blur',
                    }
                  ]"
            >
                <el-input placeholder="请输入权限名称" v-model="roleForm.name"/>
            </el-form-item>
            <el-form-item prop="sign" label="权限标识：" :rules="[{
                        required: true,
                        message: '请输入权限标识',
                        trigger: 'blur',
                    }
                  ]"
            >
                <el-input placeholder="请输入权限标识" v-model="roleForm.sign"/>
            </el-form-item>

            <el-form-item prop="desc" label="权限说明：">
                <el-input
                    v-model="roleForm.desc"
                    :rows="2"
                    type="textarea"
                    placeholder="请输入权限说明"
                />
            </el-form-item>

            <el-form-item prop="sort" label="排序：" :rules="[{
                        required: true,
                        message: '请输入排序，数字越大越靠前',
                        trigger: 'blur',
                    }
                  ]"
            >
                <el-input-number v-model="roleForm.sort" :min="1"/>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="cancelForm">取消</el-button>
                <el-button type="primary" @click="submitForm">
                    提交
                </el-button>
            </div>
        </template>
    </el-dialog>



    <el-drawer :size="400" :with-header="false" v-model="drawer" direction="ltr" >
        <template #default>
            <el-card>
                <el-text>分配菜单与按钮的权限</el-text>
            </el-card>
            <el-scrollbar style="height:calc(100vh - 132px)">
                <el-tree
                    ref="drawerRef"
                    :data="menuStore.treeMenuList"
                    default-expand-all
                    show-checkbox
                    node-key="value"

                />
            </el-scrollbar>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="drawer=false">取消</el-button>
                <el-button type="primary" @click="btnHandler">确定</el-button>
            </div>
        </template>
    </el-drawer>
</template>

<style scoped lang="less">
.demo-form-inline{
    .el-form-item{
        margin-bottom: 0;
        margin-right: 10px;
    }
}

</style>